package com.redwine.app;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.kyleduo.switchbutton.SwitchButton;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.redwine.app.adapter.SendShowImageAdapter;
import com.redwine.app.net.GsonRequest;
import com.redwine.app.net.NetworkConstants;
import com.redwine.app.net.responses.BaseResponse;
import com.redwine.app.net.responses.CountryDataResponse;
import com.redwine.app.net.responses.DownOptionsBean;
import com.redwine.app.net.responses.ProvinceDataResponse;
import com.redwine.app.net.responses.UploadImagesResponse;
import com.redwine.app.net.responses.WineCategoryDataResponse;
import com.redwine.app.net.responses.WineInfoResponse;
import com.redwine.app.utils.DimenUtils;
import com.redwine.app.utils.Global;
import com.redwine.app.utils.Utils;
import com.redwine.app.view.CommonPopupListWindow;
import com.redwine.app.view.MeasureGridView;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * 我发布的货源修改界面
 * 作者：gassion on 17/9/11 18:26
 * 最可怕的敌人，就是没有坚强的信念。
 */
public class MyPublishedSourcesUpdateActivity extends BaseActivity {

    @ViewInject(R.id.update_tv_wine_origin)
    TextView updateTvWineOrigin;
    @ViewInject(R.id.update_tv_wine_home)
    TextView updateTvWineHome;
    @ViewInject(R.id.update_et_wine_name)
    EditText updateEtWineName;
    @ViewInject(R.id.update_sb_price_public)
    SwitchButton updateSbPricePublic;
    @ViewInject(R.id.update_et_bottle)
    EditText updateEtBottle;
    @ViewInject(R.id.update_et_price)
    EditText updateEtPrice;
    @ViewInject(R.id.update_tv_wine_type)
    TextView updateTvWineType;
    @ViewInject(R.id.update_et_requirements)
    EditText updateEtRequirements;
    @ViewInject(R.id.update_measure_grid_view)
    MeasureGridView updateMeasureGridView;
    @ViewInject(R.id.header_title)
    private TextView headerTitle;
    @ViewInject(R.id.layout_back)
    private LinearLayout layoutBack;
    private SendShowImageAdapter sendShowImageAdapter;
    public static final String PUBLISH_ID = "PUBLISH_ID";
    private List<UploadImagesResponse.DataEntity> uploadImagesResponses = new ArrayList<>();
    private List<DownOptionsBean> mCategoryLists = new ArrayList<>();//种类
    private List<DownOptionsBean> mCityLists = new ArrayList<>();//所在地
    private List<DownOptionsBean> mCountryLists = new ArrayList<>();//产地
    private String mPublishId;
    private String mCategory;
    private String mCity;
    private String mProduce;
    private String mName;
    private String mSwitch;
    private String mPrice;
    private String mNum;
    private String mContent;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_published_sources_update);
        ViewUtils.inject(this);
        initView();
        requestWineInfoData();

    }

    private void initView() {
        headerTitle.setText(getString(R.string.modify_the));
        layoutBack.setVisibility(View.VISIBLE);
        if (null != getIntent()) {
            mPublishId = getIntent().getStringExtra(PUBLISH_ID);
        } else {
            finish();
        }
        sendShowImageAdapter = new SendShowImageAdapter(this);
        sendShowImageAdapter.setAddImagesListener(new SendShowImageAdapter.AddImageListener() {
            @Override
            public void onClickListener() {
                choosePhotoDialog();
            }
        });
        updateMeasureGridView.setAdapter(sendShowImageAdapter);
    }


    @OnClick({R.id.layout_back, R.id.update_tv_save_changes, R.id.update_tv_wine_origin, R.id.update_tv_wine_home, R.id.update_tv_wine_type})
    public void mClick(View view) {
        switch (view.getId()) {

            case R.id.layout_back:
                finish();
                break;

            case R.id.update_tv_save_changes:
                submitData();
                break;

            case R.id.update_tv_wine_origin:
                showDownOptions(updateTvWineOrigin, mCountryLists);
                break;

            case R.id.update_tv_wine_type:
                showDownOptions(updateTvWineType, mCategoryLists);
                break;

            case R.id.update_tv_wine_home:
                showDownOptions(updateTvWineHome, mCityLists);
                break;
        }
    }


    /**
     * 提交数据
     */
    private void submitData() {
        if (TextUtils.isEmpty(mProduce)) {
            Utils.showToast("产地不能为空!");
            return;
        }

        if (TextUtils.isEmpty(mCity)) {
            Utils.showToast("所在地不能为空!");
            return;
        }

        if (TextUtils.isEmpty(updateEtWineName.getText().toString())) {
            Utils.showToast("品牌名称不能为空!");
            return;
        }
        mName = updateEtWineName.getText().toString();

        if (TextUtils.isEmpty(updateEtBottle.getText().toString())) {
            Utils.showToast("起订量不能为空!");
            return;
        } else {
            int markVal;
            try {
                markVal = Integer.valueOf(updateEtBottle.getText().toString());
            } catch (NumberFormatException e) {
                markVal = 0;
            }
            if (markVal <= 0) {
                Utils.showToast("起订量输入有误！");
                return;
            }
        }


        mNum = updateEtBottle.getText().toString();

        if (TextUtils.isEmpty(updateEtPrice.getText().toString())) {
            Utils.showToast("价格不能为空!");
            return;
        } else {
            double markVal = 0;
            try {
                markVal = Double.parseDouble(updateEtPrice.getText().toString());
            } catch (NumberFormatException e) {
                markVal = 0;
            }
            if (markVal <= 0) {
                Utils.showToast("价格输入有误！");
                return;
            }
        }
        mPrice = updateEtPrice.getText().toString();

        if (TextUtils.isEmpty(updateEtRequirements.getText().toString())) {
            Utils.showToast("酒品描述不能为空!");
            return;
        }
        mContent = updateEtRequirements.getText().toString();

        if (null == uploadImagesResponses || uploadImagesResponses.isEmpty()) {
            Utils.showToast("货源图片不能为空!");
            return;
        }

        mSwitch = updateSbPricePublic.isChecked() ? "1" : "2";

        showWaiting();
        UploadHelper uploadHelper = new UploadHelper(uploadImagesResponses);
        uploadHelper.uploadFile(new UploadHelper.UploadListener() {
            @Override
            public void onUploadComplete(boolean isSuccess, String str) {
                if (isSuccess) {
                    requestSavePublishData(str);
                } else {
                    Utils.showToast("上传图片错误请重试！");
                }
            }
        });
    }

    /**
     * 修改供应详情
     */
    private void requestWineInfoData() {
        showWaiting();
        String url = NetworkConstants.DELETE_WINE_INFO_URL;
        Map<String, String> params = new LinkedHashMap<>();
        params.put("publish_id", mPublishId);
        GsonRequest<WineInfoResponse> request = new GsonRequest<>(url, Request.Method.POST,
                WineInfoResponse.class, false, params, new Response.Listener<WineInfoResponse>() {
            @Override
            public void onResponse(WineInfoResponse response) {
                if (response.isSuccess()) {
                    requestWineCategoryData();
                    WineInfoResponse.DataEntity responseData = response.getData();
                    updateViews(responseData);
                } else {
                    dismissWaiting();
                    Utils.showToast(response.getMsg());
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                dismissWaiting();
                Utils.showToast(error.getMessage());
            }
        });
        APP.getInstance().getRequestQueue().add(request);
    }


    /**
     * 保存提交供应详情
     */
    private void requestSavePublishData(String str) {
        String url = NetworkConstants.DELETE_SAVE_PUBLISH_URL;
        Map<String, String> params = new LinkedHashMap<>();
        params.put("publish_id", mPublishId);
        params.put("category", mCategory);
        params.put("city", mCity);
        params.put("produce", mProduce);
        params.put("name", mName);
        params.put("switch", mSwitch);
        params.put("price", mPublishId);
        params.put("num", mNum);
        params.put("content", mContent);
        params.put("images", str);
        GsonRequest<BaseResponse> request = new GsonRequest<>(url, Request.Method.POST,
                BaseResponse.class, false, params, new Response.Listener<BaseResponse>() {
            @Override
            public void onResponse(BaseResponse response) {
                dismissWaiting();
                if (response.isSuccess()) {
                    finish();
                } else {
                    Utils.showToast(response.getMsg());
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Utils.showToast(error.getMessage());
                dismissWaiting();
            }
        });
        APP.getInstance().getRequestQueue().add(request);
    }

    /**
     * 更新views
     *
     * @param responseData
     */
    private void updateViews(WineInfoResponse.DataEntity responseData) {
        mCategory = responseData.getCategory_id();
        mCity = responseData.getCity_id();
        mProduce = responseData.getProduce_id();
        mName = responseData.getName();
        mSwitch = responseData.getSwitchX();
        mPrice = responseData.getPrice();
        mNum = responseData.getNum();
        List<String> list = strConvertList(responseData.getPic());
        for (int i = 0; i < list.size(); i++) {
            UploadImagesResponse.DataEntity data = new UploadImagesResponse.DataEntity();
            data.setReal_url(list.get(i));
            uploadImagesResponses.add(data);
        }
        sendShowImageAdapter.setData(uploadImagesResponses);
        updateTvWineOrigin.setText(responseData.getProduce());
        updateTvWineHome.setText(responseData.getCity());
        updateTvWineType.setText(responseData.getCategory());
        if ("1".equals(mSwitch)) {
            updateSbPricePublic.setCheckedImmediately(true);
        } else {
            updateSbPricePublic.setCheckedImmediately(false);
        }
        updateEtWineName.setText(mName);
        updateEtBottle.setText(mNum);
        updateEtPrice.setText(mPrice);
        updateEtRequirements.setText(responseData.getContent());
    }

    @Override
    protected void photoCallBack(String path) {
        UploadImagesResponse.DataEntity data = new UploadImagesResponse.DataEntity();
        data.setLocalPath(path);
        uploadImagesResponses.add(data);
        sendShowImageAdapter.setData(uploadImagesResponses);
    }


    /**
     * 发布货源获取酒种类
     */
    private void requestWineCategoryData() {
        String url = NetworkConstants.PUBLISH_WINE_CATEGORY_URL;
        Map<String, String> params = new LinkedHashMap<>();
        params.put("uid", Global.user.getUid());
        GsonRequest<WineCategoryDataResponse> request = new GsonRequest<>(url, Request.Method.POST,
                WineCategoryDataResponse.class, false, params, new Response.Listener<WineCategoryDataResponse>() {
            @Override
            public void onResponse(WineCategoryDataResponse response) {
                if (response.isSuccess()) {
                    WineCategoryDataResponse.DataEntity responseData = response.getData();
                    List<WineCategoryDataResponse.DataEntity.CategoryEntity> responseDataCategory = responseData.getCategory();
                    for (int i = 0; i < responseDataCategory.size(); i++) {
                        DownOptionsBean downOptionsBean = new DownOptionsBean();
                        downOptionsBean.setName(responseDataCategory.get(i).getName());
                        downOptionsBean.setId(responseDataCategory.get(i).getId());
                        mCategoryLists.add(downOptionsBean);
                    }
                    requestProvinceData();
                } else {
                    dismissWaiting();
                    Utils.showToast(response.getMsg());
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                dismissWaiting();
                Utils.showToast(error.getMessage());
            }
        });
        APP.getInstance().getRequestQueue().add(request);
    }

    /**
     * 获取省
     */
    private void requestProvinceData() {
        String url = NetworkConstants.GET_PROVINCE_URL;
        Map<String, String> params = new LinkedHashMap<>();
        params.put("uid", Global.user.getUid());
        GsonRequest<ProvinceDataResponse> request = new GsonRequest<>(url, Request.Method.POST,
                ProvinceDataResponse.class, false, params, new Response.Listener<ProvinceDataResponse>() {
            @Override
            public void onResponse(ProvinceDataResponse response) {
                if (response.isSuccess()) {
                    ProvinceDataResponse.DataEntity responseData = response.getData();
                    mCityLists = responseData.getCity();
                    requestCountryData();
                } else {
                    dismissWaiting();
                    Utils.showToast(response.getMsg());
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                dismissWaiting();
                Utils.showToast(error.getMessage());
            }
        });
        APP.getInstance().getRequestQueue().add(request);
    }

    /**
     * 获取国家
     */
    private void requestCountryData() {
        String url = NetworkConstants.COUNTRY_URL;
        Map<String, String> params = new LinkedHashMap<>();
        params.put("uid", Global.user.getUid());
        GsonRequest<CountryDataResponse> request = new GsonRequest<>(url, Request.Method.POST,
                CountryDataResponse.class, false, params, new Response.Listener<CountryDataResponse>() {
            @Override
            public void onResponse(CountryDataResponse response) {
                dismissWaiting();
                if (response.isSuccess()) {
                    CountryDataResponse.DataEntity responseData = response.getData();
                    List<CountryDataResponse.DataEntity.CountryEntity> country = responseData.getCountry();
                    for (int i = 0; i < country.size(); i++) {
                        DownOptionsBean downOptionsBean = new DownOptionsBean();
                        downOptionsBean.setName(country.get(i).getName());
                        downOptionsBean.setId(country.get(i).getId());
                        mCountryLists.add(downOptionsBean);
                    }
                } else {
                    dismissWaiting();
                    Utils.showToast(response.getMsg());
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                dismissWaiting();
                Utils.showToast(error.getMessage());
            }
        });
        APP.getInstance().getRequestQueue().add(request);
    }

    /**
     * 显示下拉选项
     *
     * @param textView
     */
    private void showDownOptions(final TextView textView, final List<DownOptionsBean> stringList) {
        CommonPopupListWindow popupListWindow = new CommonPopupListWindow(this, stringList);
        popupListWindow.setOnClickListener(new CommonPopupListWindow.OnClickListener() {
            @Override
            public void onClick(int position) {
                if (textView.equals(updateTvWineOrigin)) {
                    mProduce = stringList.get(position).getId();
                } else if (textView.equals(updateTvWineHome)) {
                    mCity = stringList.get(position).getId();
                } else {
                    mCategory = stringList.get(position).getId();
                }
                textView.setText(stringList.get(position).getName());
            }
        });
        popupListWindow.showAsDropDown(textView, 0, DimenUtils.dip2px(8));
    }
}
